﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DiscoveryLogic.Analytics.DataObjects;

namespace DiscoveryLogic.Analytics.Modules.Entities
{
    /// <summary>
    /// Interaction logic for GrantListView.xaml
    /// </summary>
    public partial class GrantListView : UserControl
    {
        public delegate void OnGrantSelected(GrantDO grant);

        public event OnGrantSelected GrantSelected;

        private GrantListPresenter _Presenter;

        public GrantListView()
        {
            InitializeComponent();
        }

        public GrantListView(GrantListPresenter presneter)
			: this()
		{
			_Presenter = presneter;
			_Presenter.View = this;
		}

        public List<GrantDO> Grants
        {
            get { return this.DataContext as List<GrantDO>; }
            set
            {
                this.DataContext = value;
                if(value==null || value.Count==0)
                {
                    this.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    this.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }

        public void SubscribeEventHandler(GrantDO grant)
        {
            this._Presenter.RegisterGrantSelectionChangedEventHandler(grant);
        }

        private void lvGrants_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1)
            {
                GrantDO grant = e.AddedItems[0] as GrantDO;
                if (this.GrantSelected != null)
                    this.GrantSelected(grant);
            }
        }

        public void SelectGrant(GrantDO grant)
        {
            if (this.Grants != null && grant != null)
            {
                for (int i = 0; i < this.Grants.Count; i++)
                {
                    if (this.Grants[i].ProjectID == grant.ProjectID)
                    {
                        this.lvGrants.SelectedIndex = i;
                        break;
                    }
                }
            }
        }
    }
}
